package com.orkasgb.framework.zookeeper.lock.api;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * 用来获取客户端链接
 */
public class ZKApiClient {

    /**
     * 定义临时有序节点的父节点
     */
    private static final String locks = "/api_lock";

    /**
     * 获取客户端链接
     *
     * @return 客户端链接实例
     */
    public static ZooKeeper getZk() throws IOException, InterruptedException, KeeperException {
        ZooKeeper zk = new ZooKeeper("172.19.141.10:2181", 20000, watchedEvent -> {
        });

        /**
         * 直到客户端链接成功之后才去创建父节点
         */
        while (!zk.getState().isConnected()) {
            /**
             * 如果父节点没有创建，则去创建
             */
            if (zk.getState().isConnected()) {
                Stat stat = zk.exists(locks, false);
                if (stat == null) {
                    zk.create(locks, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
            }
        }
        return zk;
    }
}
